package com.example.mytips.createApi;

import com.example.mytips.utils.CursorLineContent;
import com.example.mytips.utils.Mye;
import com.example.mytips.utils.TextInsertUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.Messages;
import org.apache.http.util.TextUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CreateApi extends AnAction {

    private int maxParams = 7;

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        // 函数注释>这是注释
        // 函数名>apime
        // 请求地址v1开头>v1.sefji/sfjei/sef
        // 请求方式1:get,2:post>1
        // 响应是1:Map,2:List>1
        // Entity类名>Entity
        // 请求参数以逗号分隔>param1,param2

        Mye mye = Mye.builder(e);

        List<String> list = new ArrayList<>();
        for (int i = 0; i > -100; i--) {
            if (list.size() >= maxParams) {
                break;
            }

            String string = CursorLineContent.getLineContent(e, i).trim();
            string = string.replace(" ", "");
            if (!TextUtils.isEmpty(string)) {
                list.add(string);
            }
        }
        Collections.reverse(list);

        if (list.size() < maxParams) {
            Messages.showInfoMessage(mye.project, "6个参数缺一不可", "提示");
            return;
        }

        String notes = getValue(list.get(0));
        String funName = getValue(list.get(1));
        String url = getValue(list.get(2));
        String method = getValue(list.get(3));
        String bodyType = getValue(list.get(4));
        String entityName = getValue(list.get(5));
        String params = getValue(list.get(6));

        if (TextUtils.isEmpty(notes) || TextUtils.isEmpty(funName) || TextUtils.isEmpty(url) || TextUtils.isEmpty(method) || TextUtils.isEmpty(entityName) || TextUtils.isEmpty(bodyType)) {
            Messages.showInfoMessage(mye.project, "所有的>后面都要有值", "提示");
            return;
        }

        String string = CreateApiUtil.createApi(notes, funName, url, method, bodyType, entityName, params);
        TextInsertUtil.insertString(e, string);
    }

    public String getValue(String value) {
        if (TextUtils.isEmpty(value)) return "";

        List<String> split = Arrays.stream(value.split(">")).toList();
        if (split.size() > 1) {
            return split.get(1);
        }

        return "";
    }
}
